package org.corey.share.db.dao;

import java.util.List;

import javax.persistence.Query;

import org.corey.share.db.entity.CoreyFile;
import org.corey.share.misc.PageData;

@SuppressWarnings("unchecked")
public class CoreyFileDaoImpl extends DefaultBaseDao implements CoreyFileDao {

	public PageData findAll(int pageSize, int pageIndex, String orderBy) {
		int startRecordIndex = PageData.getStartIndex(pageSize, pageIndex);
		Query query = getEM().createQuery("Select f from CoreyFile f order by "
				+ orderBy);
		query.setFirstResult(startRecordIndex);
		query.setMaxResults(pageSize);
		List<CoreyFile> pageData = query.getResultList();
		Query countQuery = getEM().createQuery("Select count(f) from CoreyFile f");
		int totalSize = this.getCount(countQuery);
		PageData<CoreyFile> articles = new PageData<CoreyFile>(totalSize,
				pageSize, pageIndex, pageData);
		return articles;
	}

	public boolean deleteFile(Long user, String respository,
			String serverSideFileName) {
		CoreyFile file = this.getCoreyFileByUrl(user, respository,
				serverSideFileName);
		if (file != null) {
			this.remove(file);
		}
		return true;
	}

	public CoreyFile getCoreyFileByUrl(Long user, String respository,
			String serverSideFileName) {
		Query query = getEM()
				.createQuery("SELECT c FROM CoreyFile c WHERE c.serverSideFileName=:serverSideFileName");
		query.setParameter("user", user);
		query.setParameter("respository", respository);
		query.setParameter("serverSideFileName", serverSideFileName);
		CoreyFile file = (CoreyFile) query.getSingleResult();
		return file;
	}

	public List<CoreyFile> getCoreyFilesByUser(Long user, String respository) {
		Query query = getEM()
				.createQuery("SELECT FROM CoreyFile c WHERE c.user=:user and c.respository=:respository");
		query.setParameter("user", user);
		query.setParameter("respository", respository);
		List<CoreyFile> files = query.getResultList();
		return files;
	}

	public boolean deleteFile(Long id) {
		CoreyFile file = (CoreyFile) this.load(id, CoreyFile.class);
		if (file != null) {
			this.remove(file);
		}
		return true;
	}

	public boolean saveFile(CoreyFile file) {
		this.save(file);
		return true;
	}

	public CoreyFile getFileById(Long id) {
		return (CoreyFile)this.load(id, CoreyFile.class);
	}

}
